<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="第五章：内存管理(1)ARC 几乎把所有内存管理事宜都交由编译器来决定，开发者只需专注于业务逻辑。   第29条：理解引用计数Objective-C 语言使用引用计数来管理内存，每个对象都有个可以递增或递减的计数器。如果想使某个对象继续存活，那就递增其引用计数；用完了之后，就递减其计数。计数变为0，就表示没人关注此对象了，于是，就可以把它销毁。 引用计数的工作原理在引用计数架构下，对象有个计数器，">
<meta property="og:type" content="article">
<meta property="og:title" content="《Effective Objective-C 2.0》第五章阅读笔记(1)">
<meta property="og:url" content="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%94%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="第五章：内存管理(1)ARC 几乎把所有内存管理事宜都交由编译器来决定，开发者只需专注于业务逻辑。   第29条：理解引用计数Objective-C 语言使用引用计数来管理内存，每个对象都有个可以递增或递减的计数器。如果想使某个对象继续存活，那就递增其引用计数；用完了之后，就递减其计数。计数变为0，就表示没人关注此对象了，于是，就可以把它销毁。 引用计数的工作原理在引用计数架构下，对象有个计数器，">
<meta property="og:locale">
<meta property="og:image" content="http://ovsbvt5li.bkt.clouddn.com/18-5-8/55922608.jpg">
<meta property="article:published_time" content="2018-05-07T16:00:00.000Z">
<meta property="article:modified_time" content="2022-08-12T09:27:18.585Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="Effective Objective-C 2.0">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ovsbvt5li.bkt.clouddn.com/18-5-8/55922608.jpg">


<link rel="canonical" href="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%94%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%94%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/","path":"2018/05/2018/05/《Effective Objective-C 2.0》第五章阅读笔记(1)/","title":"《Effective Objective-C 2.0》第五章阅读笔记(1)"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>《Effective Objective-C 2.0》第五章阅读笔记(1) | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC%E4%BA%94%E7%AB%A0%EF%BC%9A%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86-1"><span class="nav-number">1.</span> <span class="nav-text">第五章：内存管理(1)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC29%E6%9D%A1%EF%BC%9A%E7%90%86%E8%A7%A3%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0"><span class="nav-number">1.1.</span> <span class="nav-text">第29条：理解引用计数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0%E7%9A%84%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86"><span class="nav-number">1.1.1.</span> <span class="nav-text">引用计数的工作原理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%B0%83%E7%94%A8-release-%E4%B9%8B%E5%90%8E%EF%BC%8C%E5%B0%B1%E5%B7%B2%E7%BB%8F%E6%97%A0%E6%B3%95%E4%BF%9D%E8%AF%81%E6%89%80%E6%8C%87%E7%9A%84%E5%AF%B9%E8%B1%A1%E4%BB%8D%E7%84%B6%E5%AD%98%E6%B4%BB"><span class="nav-number">1.1.1.1.</span> <span class="nav-text">调用 release 之后，就已经无法保证所指的对象仍然存活</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B1%9E%E6%80%A7%E5%AD%98%E5%8F%96%E6%96%B9%E6%B3%95%E4%B8%AD%E7%9A%84%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86"><span class="nav-number">1.1.2.</span> <span class="nav-text">属性存取方法中的内存管理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%87%AA%E5%8A%A8%E9%87%8A%E6%94%BE%E6%B1%A0"><span class="nav-number">1.1.3.</span> <span class="nav-text">自动释放池</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%95%E7%94%A8%E5%BE%AA%E7%8E%AF"><span class="nav-number">1.1.4.</span> <span class="nav-text">引用循环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">1.1.5.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC30%E6%9D%A1%EF%BC%9A%E7%94%A8-ARC-%E7%AE%80%E5%8C%96%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0"><span class="nav-number">1.2.</span> <span class="nav-text">第30条：用 ARC 简化引用计数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-ARC-%E6%97%B6%E5%BF%85%E9%A1%BB%E9%81%B5%E5%BE%AA%E7%9A%84%E6%96%B9%E6%B3%95%E5%91%BD%E5%90%8D%E8%A7%84%E5%88%99"><span class="nav-number">1.2.1.</span> <span class="nav-text">使用 ARC 时必须遵循的方法命名规则</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ARC-%E5%A6%82%E4%BD%95%E6%B8%85%E7%90%86%E5%AE%9E%E4%BE%8B%E5%8F%98%E9%87%8F"><span class="nav-number">1.2.2.</span> <span class="nav-text">ARC 如何清理实例变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93-1"><span class="nav-number">1.2.3.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%94%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="《Effective Objective-C 2.0》第五章阅读笔记(1) | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《Effective Objective-C 2.0》第五章阅读笔记(1)
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-05-08 00:00:00" itemprop="dateCreated datePublished" datetime="2018-05-08T00:00:00+08:00">2018-05-08</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2022-08-12 17:27:18" itemprop="dateModified" datetime="2022-08-12T17:27:18+08:00">2022-08-12</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第五章：内存管理-1"><a href="#第五章：内存管理-1" class="headerlink" title="第五章：内存管理(1)"></a><center>第五章：内存管理(1)</center></h1><p>ARC 几乎把所有内存管理事宜都交由编译器来决定，开发者只需专注于业务逻辑。  </p>
<h2 id="第29条：理解引用计数"><a href="#第29条：理解引用计数" class="headerlink" title="第29条：理解引用计数"></a>第29条：理解引用计数</h2><p>Objective-C 语言使用引用计数来管理内存，每个对象都有个可以递增或递减的计数器。如果想使某个对象继续存活，那就递增其引用计数；用完了之后，就递减其计数。计数变为0，就表示没人关注此对象了，于是，就可以把它销毁。</p>
<h3 id="引用计数的工作原理"><a href="#引用计数的工作原理" class="headerlink" title="引用计数的工作原理"></a>引用计数的工作原理</h3><p>在引用计数架构下，对象有个计数器，用以表示当前有多少个事物想令此对象继续存活下去。这在 Objective-C 中叫做“引用计数”（reference count）。NSObject协议声明了下面三个方法用于操作计数器，以递增或递减其值：<br>retain：递增保留计数。<br>release：递减保留计数。<br>autorelease：待稍后清理“自动释放池”（autorelease pool）时，再递减保留计数。  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">@protocol</span> <span class="title">NSObject</span></span></span><br><span class="line"></span><br><span class="line">- (<span class="keyword">instancetype</span>)<span class="keyword">retain</span> OBJC_ARC_UNAVAILABLE;</span><br><span class="line">- (<span class="keyword">oneway</span> <span class="type">void</span>)release OBJC_ARC_UNAVAILABLE;</span><br><span class="line">- (<span class="keyword">instancetype</span>)autorelease OBJC_ARC_UNAVAILABLE;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>
<p>对象创建出来时，其引用计数至少为1。若想令其继续存活，则调用 retain 方法。要是某部分代码不再使用此对象，不想令其继续存活，那就调用 release 或 autorelease 方法。最终当引用计数归零时，对象就回收了（deallocated），也就是说，系统会将其占用的内存标记为“可重用”（reuse）。此时，所有指向该对象的引用也都变得无效了。</p>
<h4 id="调用-release-之后，就已经无法保证所指的对象仍然存活"><a href="#调用-release-之后，就已经无法保证所指的对象仍然存活" class="headerlink" title="调用 release 之后，就已经无法保证所指的对象仍然存活"></a>调用 release 之后，就已经无法保证所指的对象仍然存活</h4><p>例如：  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSNumber</span> *number = [[<span class="built_in">NSNumber</span> alloc] initWithInt:<span class="number">1234</span>];</span><br><span class="line">[array addObject:number];</span><br><span class="line">[number release];</span><br><span class="line"><span class="built_in">NSLog</span>(<span class="string">@&quot;number = %@&quot;</span>,number);</span><br></pre></td></tr></table></figure>
<p>调用 release 之后，其引用计数降至0，那么 number 对象所占内存也许会回收，那么再调用NSLog可能会使应用程序崩溃。这里说“可能”，是因为对象所占的内存在“解除分配”（deallocated）之后，只是放回“可用内存池”（avaliable pool）。如果执行 NSLog 时尚未覆写对象内存，那么该对象仍然有效，这时程序不会崩溃。</p>
<h3 id="属性存取方法中的内存管理"><a href="#属性存取方法中的内存管理" class="headerlink" title="属性存取方法中的内存管理"></a>属性存取方法中的内存管理</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)setFoo:(<span class="type">id</span>)foo &#123;</span><br><span class="line">    [foo <span class="keyword">retain</span>];</span><br><span class="line">    [_foo release];</span><br><span class="line">    _foo = foo;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里需要注意的是必须先 retain 对象，然后再 release 。原因就是新对象和旧对象可能是同一个对象，这时如果先 release 这个对象，可能会导致系统永久回收对象。之后再 retain 也无法再复生。</p>
<h3 id="自动释放池"><a href="#自动释放池" class="headerlink" title="自动释放池"></a>自动释放池</h3><p>调用 release 会立刻递减对象的保留计数，而且还有可能令系统回收此对象，然而有时候可以不调用它，改为调用 autorelease ，此方法会在稍后递减计数，通常是在下一次“事件循环”（event loop）时递减，不过也可能执行得更早些（why ？？后面会提到）。<br>这个特性很有用，例如：  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="built_in">NSString</span> *)stringValue &#123;</span><br><span class="line">    <span class="built_in">NSString</span> *str = [[<span class="built_in">NSString</span> alloc] initWithFormat:<span class="string">@&quot;I am this: %@&quot;</span>,<span class="keyword">self</span>];</span><br><span class="line">    <span class="keyword">return</span> str;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在 MRC 环境下，此时 str 对象的引用计数会比期望值多1 ，因为 alloc 会使引用计数加1，但却没有释放。这时就应该用 autorelease 。此方法可以保证对象在跨越“方法调用边界”（method call boundary）后一定存活。实际上，释放操作会在清空最外层的自动释放池时执行，除非你有自己的自动释放池，否则这个时机指的就是当前线程的下一次事件循环。    </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="built_in">NSString</span> *)stringValue &#123;</span><br><span class="line">    <span class="built_in">NSString</span> *str = [[<span class="built_in">NSString</span> alloc] initWithFormat:<span class="string">@&quot;I am this: %@&quot;</span>,<span class="keyword">self</span>];</span><br><span class="line">    <span class="keyword">return</span> [str autorelease];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="引用循环"><a href="#引用循环" class="headerlink" title="引用循环"></a>引用循环</h3><p>使用引用计数机制时，经常要注意的一个问题就是“引用循环”（retain cycle），也就是呈环状相互引用的多个对象（如下图）。这将导致内存泄露，因为循环中的对象其引用计数都不会为0。<br><img src="http://ovsbvt5li.bkt.clouddn.com/18-5-8/55922608.jpg"></p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>引用计数机制通过可以递增递减的计数机制来管理内存。对象创建好之后，其引用计数至少为1。若引用计数为正，则对象继续存活。当引用计数降为0时，对象就被销毁了。<br>在对象生命期中，其余对象通过引用来保留或释放此对象。保留与释放操作分别会递增及递减保留计数。</p>
<h2 id="第30条：用-ARC-简化引用计数"><a href="#第30条：用-ARC-简化引用计数" class="headerlink" title="第30条：用 ARC 简化引用计数"></a>第30条：用 ARC 简化引用计数</h2><p>在 MRC 环境下，下面代码会出现内存泄漏问题   </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> ([<span class="keyword">self</span> showLogMsg]) &#123;</span><br><span class="line">	<span class="built_in">NSString</span> *str = [[<span class="built_in">NSString</span> alloc] initWithFormat:<span class="string">@&quot;I am this: %@&quot;</span>,<span class="keyword">self</span>];</span><br><span class="line">	<span class="built_in">NSLog</span>(<span class="string">@&quot;%@&quot;</span>,str);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>原因是 if 语句结束后，并没有释放 str 对象。所以我们必须手动去释放</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> ([<span class="keyword">self</span> showLogMsg]) &#123;</span><br><span class="line">	<span class="built_in">NSString</span> *str = [[<span class="built_in">NSString</span> alloc] initWithFormat:<span class="string">@&quot;I am this: %@&quot;</span>,<span class="keyword">self</span>];</span><br><span class="line">	<span class="built_in">NSLog</span>(<span class="string">@&quot;%@&quot;</span>,str);</span><br><span class="line">	[str release];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>而这个操作完全可以交给 ARC (Automatic Reference Counting)来完成，也就是在 ARC 环境下，编译器会在编译时会自动加上内存管理语句。<br>由于 ARC 会自动执行retain、release、autorelease等操作，所以直接在 ARC 下调用这些内存管理方法是非法的。具体来说，不能调用下列方法：<br><strong>retain<br>release<br>autorelease<br>dealloc</strong><br>实际上，ARC在调用这些方法时，并不通过普通的 Objective-C 消息派发机制，而是直接调用其底层C语言版本。这样做性能更好，因为保留及释放操作需要频繁执行，所以直接调用底层函数能节省很多CPU周期。  </p>
<h3 id="使用-ARC-时必须遵循的方法命名规则"><a href="#使用-ARC-时必须遵循的方法命名规则" class="headerlink" title="使用 ARC 时必须遵循的方法命名规则"></a>使用 ARC 时必须遵循的方法命名规则</h3><p>将内存管理语义在方法名中表示出来早已成为 Objective-C 的惯例，而 ARC 则将之确立为硬性规定。这些规则简单地体现在方法名上。若方法名以下列词语开头，则其返回的对象归调用者所有：<br><strong>alloc<br>new<br>copy<br>mutableCopy</strong><br>归调用者所有的意思是：<strong>调用上述四种方法的那段代码要负责释放方法所返回的对象。</strong><br>举个例子，演示了ARC的用法：  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法名以关键字 new 开头，ARC 不会加入 retain、release 或 autorelease 语句。</span></span><br><span class="line">+ (EOCPerson *)newPerson &#123;</span><br><span class="line">	EOCPerson *person = [[EOCPerson alloc] init]; </span><br><span class="line">	<span class="keyword">return</span> person; </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法名不以关键字开头，ARC 会自动加上 autorelease 语句。</span></span><br><span class="line">+ (EOCPerson *)somePerson &#123;</span><br><span class="line">	EOCPerson *person = [[EOCPerson alloc] init]; </span><br><span class="line">	<span class="keyword">return</span> person; </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ARC 会在函数末尾给 personOne 加上 release 语句。</span></span><br><span class="line">- (<span class="type">void</span>)doSomething &#123;</span><br><span class="line">	EOCPerson *personOne = [EOCPerson newPerson]; </span><br><span class="line">	EOCPerson *personTwo = [EOCPerson somePerson]; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>除了会自动调用“保留”与“释放”方法外，ARC 还可以执行一些手工操作很难甚至无法完成的优化。如果发现在同一个对象上执行多次“保留”与“释放”操作，那么ARC有时可以成对地移除这两个操作。  </p>
<p>一般，在方法中返回自动释放的对象时，要执行一个特殊函数。此时不直接调用对象的 autorelease 方法，而是改为调用 objc_autoreleaseReturnValue 。此函数会检视当前方法返回之后即将要执行的那段代码。若发现那段代码在返回的对象上执行 retain 操作，则设置全局数据结构（此数据结构的具体内容因处理器而异）中的一个标志位而不执行 autorelease 操作。与之相似，如果方法返回了一个自动释放的对象，而调用方法的代码要保留此对象，那么此时不直接执行 retain，而是改为执行objc_retainAutoreleaseReturnValue 函数。此函数要检测刚才提到的那个标志位，若已经置位，则不执行 retain 操作。设置并检测标志位，要比调用 autorelease 和 retain 更快。</p>
<h3 id="ARC-如何清理实例变量"><a href="#ARC-如何清理实例变量" class="headerlink" title="ARC 如何清理实例变量"></a>ARC 如何清理实例变量</h3><p>ARC 会在 dealloc 方法中自动生成回收对象时所执行的代码。ARC 会借用 Objective-C++ 的一项特性来生成清理例程（cleanup routime）。回收 Objective-C++ 对象时，待回收的对象会调用所有C++对象的析构函数（destructor）。编译器如果发现某个对象里含有C++对象，就会生成名为.cxx_destruct的方法。而ARC则借助此特性，在该方法中生成清理内存所需的代码。<br>如果有非 Objective-C 的对象，比如 CoreFoundation 中的对象或是由malloc()分配在堆中的内存，那么仍然需要手动清理。</p>
<h3 id="总结-1"><a href="#总结-1" class="headerlink" title="总结"></a>总结</h3><p>用ARC管理内存，可省去类中的许多的“样板代码”。<br>ARC会在合适的地方插入“保留”及“释放”对象。<br>CoreFoundation 对象不归 ARC 管理，开发者必须实时调用 CFRetain&#x2F;CFRelease 手动释放。  </p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Effective-Objective-C-2-0/" rel="tag"># Effective Objective-C 2.0</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%9B%9B%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/" rel="prev" title="《Effective Objective-C 2.0》第四章阅读笔记">
                  <i class="fa fa-chevron-left"></i> 《Effective Objective-C 2.0》第四章阅读笔记
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%94%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(3)/" rel="next" title="《Effective Objective-C 2.0》第五章阅读笔记(3)">
                  《Effective Objective-C 2.0》第五章阅读笔记(3) <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
